﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Xml.Linq;
using System.IO;
using System.Web.UI;
using MyAlbum.Model;
using System.Web.Mvc;
using System.Web.Routing;
using MyAlbum.Services;

namespace PersonalAlbum
{
    public class PostOffice
    {
        private IConfiguration _configuration;
        public PostOffice(IConfiguration configuration)
        {
            this._configuration = configuration;
        }
        public void SendConfirmationEmail(string email, string userName, string link, RequestContext requestContext)
        {
            XDocument doc = XDocument.Parse(File.ReadAllText(Path.Combine(ConfigManager.AppDataPhysicalPath, "RegistrationConfirmation.xml")));
            MailMessage message = new MailMessage();
            message.IsBodyHtml = true;
            message.Subject = (from s in doc.Descendants("Subject") select s.Value.Trim()).Single()
                .Replace("$siteName$", this._configuration.SiteTitle)
                .Replace("$userName$", HttpUtility.HtmlEncode(userName));
            string body = (from s in doc.Descendants("Body") select s.Value.Trim()).Single();
            body = body.Replace("$siteName$", this._configuration.SiteTitle);
            body = body.Replace("$userName$", HttpUtility.HtmlEncode(userName));

            var siteUrl = ConfigManager.SiteUrl;
            UrlHelper url = new UrlHelper(requestContext);
            var confirmationPage = siteUrl + url.Action("ConfirmRegistration", "Account");//a link the entry view
            body = body.Replace("$confirmationPage$", confirmationPage);
            var confirmationLink = siteUrl + url.Action("ConfirmRegistration", "Account", new { confirmationCode = link });//a link the entry view
            body = body.Replace("$confirmationLink$", confirmationLink);
            message.Body = body;
            message.To.Add(email);
            message.From = new MailAddress(this._configuration.MailFromAddress, "support");

            Mailer.Send(message);
        }
        public void NotifyNewReply(Reply reply)
        {
            StringWriter sw = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(sw);
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Subject");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(reply.Subject));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("From");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(reply.Email));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Body");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(reply.Body));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr
            MailMessage message = new MailMessage(this._configuration.MailFromAddress, this._configuration.AdminEmail, "A new reply on your site", writer.InnerWriter.ToString());
            message.IsBodyHtml = true;
            Mailer.Send(message);
        }

        public  void SentToFriend(string email, string text, string senderName, Entry entry, RequestContext requestContext)
        {
            XDocument doc = XDocument.Parse(File.ReadAllText(Path.Combine(ConfigManager.AppDataPhysicalPath, "SendToFriend.xml")));
            MailMessage message = new MailMessage();
            message.IsBodyHtml = true;
            message.Subject = (from s in doc.Descendants("Subject") select s.Value.Trim()).Single().Replace("$sendername$", HttpUtility.HtmlEncode(senderName));
            string body = (from s in doc.Descendants("Body") select s.Value.Trim()).Single();
            body = body.Replace("$usertext$", HttpUtility.HtmlEncode(text));
            body = body.Replace("$sendername$", HttpUtility.HtmlEncode(senderName));
            /*TODO fix to work with non root sites*/

            var siteUrl = ConfigManager.SiteUrl;
            var entryDirectUrl = siteUrl + "/" + ConfigManager.ImagesPath.TrimStart('/', '~').TrimEnd('/') + "/" + entry.Uri;//a direct raw view of the entry
            UrlHelper url = new UrlHelper(requestContext);
            var entryUrl = siteUrl + url.Action("Details", "entry", new { id = entry.Id });//a link the entry view
            body = body.Replace("$entryUrl$", entryUrl);
            body = body.Replace("$entryDirectUrl$", entryDirectUrl);
            body = body.Replace("$entryName$", HttpUtility.HtmlEncode(entry.Title));
            body = body.Replace("$siteUrl$", siteUrl);
            message.Body = body;
            message.To.Add(email);
            message.From = new MailAddress(this._configuration.MailFromAddress, "support");

            Mailer.Send(message);
        }

        private SmtpClient Mailer
        {
            get
            {
                SmtpClient client = new SmtpClient(this._configuration.MailHost);
                if (!string.IsNullOrEmpty(this._configuration.MailUserName) &&
                    !string.IsNullOrEmpty(this._configuration.MailPassword))
                {
                    client.Credentials = new System.Net.NetworkCredential(this._configuration.MailUserName, this._configuration.MailPassword);
                }
                WebLogger.Trace("sending using " + this._configuration.MailHost + "," + this._configuration.MailUserName + "," + this._configuration.MailPassword);
                return client;
            }
        }

        public void NotifySupport(Support support)
        {
            StringWriter sw = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(sw);
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Subject");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(support.Subject));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("From");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(support.Email));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Name");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(support.Name));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("Body");
            writer.RenderEndTag();//td
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(HttpContext.Current.Server.HtmlEncode(support.Body));
            writer.RenderEndTag();//td
            writer.RenderEndTag();//tr
            MailMessage message = new MailMessage(this._configuration.MailFromAddress, this._configuration.AdminEmail, "A support request on your site", writer.InnerWriter.ToString());
            message.IsBodyHtml = true;
            Mailer.Send(message);
        }

        internal void SentToFriend(string email, string text, string senderName, PostEntry entry, RequestContext requestContext)
        {
            XDocument doc = XDocument.Parse(File.ReadAllText(Path.Combine(ConfigManager.AppDataPhysicalPath, "SendBlogToFriend.xml")));
            MailMessage message = new MailMessage();
            message.IsBodyHtml = true;
            message.Subject = (from s in doc.Descendants("Subject") select s.Value.Trim()).Single().Replace("$sendername$", HttpUtility.HtmlEncode(senderName));
            string body = (from s in doc.Descendants("Body") select s.Value.Trim()).Single();
            body = body.Replace("$usertext$", HttpUtility.HtmlEncode(text));
            body = body.Replace("$sendername$", HttpUtility.HtmlEncode(senderName));
            body = body.Replace("$body$", entry.Content);

            var siteUrl = ConfigManager.SiteUrl;
            UrlHelper url = new UrlHelper(requestContext);
            var entryUrl = siteUrl + url.Action("Details", "MiniBlog", new { id = entry.ID });//a link to the post view
            body = body.Replace("$entryUrl$", entryUrl);
            body = body.Replace("$entryName$", HttpUtility.HtmlEncode(entry.Title));
            body = body.Replace("$siteUrl$", siteUrl);
            message.Body = body;
            message.To.Add(email);
            message.From = new MailAddress(this._configuration.MailFromAddress, "support");

            Mailer.Send(message);
        }
    }
}
